package camid.infrastructure;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import camid.distribution.broker.Invoker;
import camid.distribution.protocol.MethodRequestMessage;
import camid.distribution.protocol.MethodResponseMessage;



public class Acceptor implements Runnable {
	
	private ObjectInputStream incomingMessageStream = null;
	private ObjectOutputStream outputMessageStream = null;
	private Socket conn;

	private Invoker invoker = null;
	private String fromHostID;
	
	private static final Logger logger = LogManager.getLogger(Acceptor.class.getName());

	public Acceptor(Invoker invoker, Socket socket){
		this.invoker = invoker;
		this.setConnection(socket);
	}
	
	public void setConnection(Socket socket){
		this.conn = socket;
	}
	
	public void run(){
		try {
		
			this.incomingMessageStream = new ObjectInputStream(this.conn.getInputStream());
			Object read = this.incomingMessageStream.readObject();
			MethodRequestMessage request = (MethodRequestMessage) read;
			MethodResponseMessage response = this.invoker.invoke(request);
			logger.info("Arrived from " + conn.getInetAddress() + ":" + conn.getPort());
			this.outputMessageStream = new ObjectOutputStream(this.conn.getOutputStream());
			this.outputMessageStream.writeObject(response);
			
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			try {
				this.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	
	private void close() throws IOException{
		this.incomingMessageStream.close();
		this.outputMessageStream.close();
		this.conn.close();
	}

	public void setFromHostID(String fromHostID) {
		this.fromHostID = fromHostID;
	}

	public String getFromHostID() {
		return fromHostID;
	}
}